package com.pms.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.controller.BaseController;
import com.pms.entity.*;
import com.pms.exception.R;
import com.pms.rpc.SystemRpcService;
import com.pms.service.*;
import com.pms.utils.WoGiaFiledConstant;
import com.pms.validator.Assert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <p>
 * 二供模块 数据监测 接口 前端控制器
 * </p>
 *
 * @author asus
 * @since 2018-07-17
 */
@RestController
@RequestMapping("/iot/dataMonitoring")
@Api(value="二供模块 数据监测 接口" ,description = "二供模块 数据监测 接口")
public class IotDataMonitoringController extends BaseController {
    @Autowired
    IIotAgencyService orgService;
    @Autowired
    IIotWaterPumpGroupService waterPumpGroupService;
    @Autowired
    IIotWaterPumpGroupAttrService waterPumpGroupAttrService;
    @Autowired
    SystemRpcService systemRpcService;
    @Autowired
    IGroupIotAgencyService groupIotAgencyService;
    @Autowired
    IIotRepairDeclareService iotRepairDeclareService;
    @Autowired
    IIotAlarmRecordService iotAlarmRecordService;
    @Autowired
    IWoGiaWpAttrService woGiaWpAttrService;
    /*
    * 实时数据信息
    * @param
    * @return
    */
    @ApiOperation(value = "实时数据信息")
    @RequestMapping(value = "/realTimePage",method ={ RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name="waterPumpGroupIds",value="左侧机构栏勾选的所有水泵组id字符串以,分割",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="communityId",value="小区id",required = false,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="houseId",value="水泵房id",required = false,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="searchValue",value="搜索框内容",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="deviceStatus",value="设备状态(0-在线,1-不在线)",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="pageSize",value="分页查询条数,默认10条",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="pageNum",value="分页查询页数",required = false,dataType = "int",paramType="form"),
    })
    public R realTimePage(String waterPumpGroupIds,Long communityId,Long houseId,String searchValue,Integer deviceStatus,Integer pageSize,Integer pageNum){
       Assert.parameterIsBlank(waterPumpGroupIds,"参数水泵组id不能为空");
        if(pageNum==null||pageNum < 1){pageNum=1;}
        if(pageSize==null||pageSize < 1){pageSize=10;}
        Page<Map<String,Object>> pages = new Page<Map<String,Object>>(pageNum,pageSize);
        // 获取当前用户角色
        Map<String,String> currentUserMap=getCurrentUserMap();
        UserInfo currentUserInfo=systemRpcService.getUserByUsername(currentUserMap.get("userName"),currentUserMap.get("companyCode"));
        Assert.isNull(currentUserInfo,"请重新登录");
        Assert.isNull(currentUserInfo.getGroupType(),"请重新登录");
        List<Long> roleWaterPumpGroupIdList = null;
//        String roleWaterPumpGroupIds = null;
        if(1!=currentUserInfo.getGroupType()){// 自定义角色
            // 获取角色拥有的 机构id
            String roleAgencyIdsStr =groupIotAgencyService.getAgencyIdsStrByGroupId(currentUserInfo.getGroupId()+"");
            Assert.parameterIsBlank(roleAgencyIdsStr,"您暂无机构权限，请联系管理员");
//           roleWaterPumpGroupIds = waterPumpGroupService.getGroupIdsStrByHouseId(roleAgencyIdsStr);
            roleWaterPumpGroupIdList = waterPumpGroupService.getGroupIdListByHouseId(roleAgencyIdsStr);
            if(roleWaterPumpGroupIdList==null||roleWaterPumpGroupIdList.isEmpty()){// 未查询到 水泵组 直接返回空数据
                pages.setRecords(null);
                return R.ok().put("data",pages);
            }
        }
       if(!waterPumpGroupIds.equals("-1")){// 查询全部 - 系统级别
           List<Long> PumpGroupIdList = new ArrayList<Long>();
           StringTokenizer strTokenizer=new StringTokenizer(waterPumpGroupIds,",");
           try {
               while (strTokenizer.hasMoreElements()) {
                   PumpGroupIdList.add(Long.parseLong(strTokenizer.nextToken()));
               }
           }catch (NumberFormatException ex){
               return R.error(400,"参数水泵组id格式错误");
           }
           if(roleWaterPumpGroupIdList!=null){
               roleWaterPumpGroupIdList.retainAll(PumpGroupIdList);// 取交集
           }
           if(roleWaterPumpGroupIdList==null){
               roleWaterPumpGroupIdList=PumpGroupIdList;//直接赋值
           }
       }
        Wrapper<Map<String,Object>> wr = new EntityWrapper<Map<String,Object>>();
        wr.eq("wpGroup.company_code",currentUserMap.get("companyCode"));
        if(communityId!=null&&communityId.longValue()!=-1L){
            wr.eq("wpGroup.community_id",communityId);
        }
        if(houseId!=null&&houseId.longValue()!=-1L){
            wr.eq("wpGroup.house_id",houseId);
        }
        if(deviceStatus!=null){
            if(deviceStatus==0){
                wr.eq("wpGroupData.deviceStatus",deviceStatus);// 设备状态
            }// 默认查询全部
            if(deviceStatus==1){
                wr.andNew("wpGroupData.deviceStatus is null");// 设备状态
            }
        }
        if(roleWaterPumpGroupIdList!=null && !roleWaterPumpGroupIdList.isEmpty() ){
            wr.in("wpGroup.group_id", roleWaterPumpGroupIdList);
        }
        if(StringUtils.isNotBlank(searchValue)){// 搜索框内容 根据 水泵房名称和水泵名称 搜索
            wr.andNew("wpGroup.house_name like '%"+searchValue+"%' or wpGroup.group_name like '%"+searchValue+"%'");
        }
        pages = waterPumpGroupService.readRealTimeDataPage(pages,wr);
        return R.ok().put("data",pages);
    }

    /*
    * 电子地图设备信息
    * @param
    * @return
    */
    @ApiOperation(value = "电子地图信息")
    @RequestMapping(value = "/readWaterPumpMapInfo",method ={ RequestMethod.POST})
    @ApiImplicitParams({
        @ApiImplicitParam(name="level",value="地图展示级别(1-小区(默认),2-水泵房)",required = true,dataType = "int",paramType="form"),
        @ApiImplicitParam(name="communityId",value="小区id",required = false,dataType = "Long",paramType="form"),
        @ApiImplicitParam(name="houseId",value="水泵房id,不为空直接默认查询(2-水泵房)级别",required = false,dataType = "Long",paramType="form"),
    })
    public R readDeciveMapInfo(Integer level,Long communityId,Long houseId){
        Assert.parameterIsNull(level,"参数level不能为空");
        if(level!=1&&level!=2){
            return R.error(400,"参数值level有误");
        }// 默认为小区 只有2级
        // 获取当前用户角色
        Map<String,String> currentUserMap=getCurrentUserMap();
        UserInfo currentUserInfo=systemRpcService.getUserByUsername(currentUserMap.get("userName"),currentUserMap.get("companyCode"));
        Assert.isNull(currentUserInfo,"请重新登录");
        Assert.isNull(currentUserInfo.getGroupType(),"请重新登录");
        String roleAgencyIdsStr = null;
        if(1!=currentUserInfo.getGroupType()) {// 自定义角色
            // 获取角色拥有的 机构id
            roleAgencyIdsStr = groupIotAgencyService.getAgencyIdsStrByGroupId(currentUserInfo.getGroupId() + "");
            Assert.parameterIsBlank(roleAgencyIdsStr, "您暂无机构权限，请联系管理员");
        }
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("companyCode",currentUserMap.get("companyCode"));
        if(roleAgencyIdsStr!=null){
            paramMap.put("roleAgencyIdsStr",roleAgencyIdsStr);
        }
        if(communityId!=null&&communityId.longValue()!=-1L){
            paramMap.put("communityId",communityId);
        }
        if(houseId!=null&&houseId.longValue()!=-1L){
//            if(level!=2){
//                return R.error(400,"参数值level有误");
//            }
            paramMap.put("houseId",houseId);
        }
        paramMap.put("level",level);
        List<Map<String,Object>> agencyMapInfoList=orgService.selectAgencyMapInfoByLevel(paramMap);
        Map<String,Map<String,Object>> communityPumpNumMap = null;
        if(level == 1){// 查询小区
            communityPumpNumMap= waterPumpGroupService.getPumpNumByCommunityId(paramMap);
        }
        if(level != 1){// 查询 水泵房
            communityPumpNumMap=  waterPumpGroupService.getPumpNumByHouseId(paramMap);
        }
        if(agencyMapInfoList==null){agencyMapInfoList = new ArrayList<Map<String,Object>>(); }
        for(int x=0,lenth=agencyMapInfoList.size();x<lenth;x++){
            Map<String,Object> pumpNumMap = communityPumpNumMap.get( agencyMapInfoList.get(x).get("id")+"" );
            if(pumpNumMap==null){
                pumpNumMap=new HashMap<String,Object>();
                pumpNumMap.put("houseId",agencyMapInfoList.get(x).get("id"));
                pumpNumMap.put("onlinePumpNum",0);
                pumpNumMap.put("nolinePumpNum",0);
                pumpNumMap.put("totalPumpNum",0);
            }
            agencyMapInfoList.get(x).putAll(pumpNumMap);
            if(agencyMapInfoList.get(x).get("totalPumpNum")==null){
                agencyMapInfoList.get(x).put("totalPumpNum",0);
                agencyMapInfoList.get(x).put("onlinePumpNum",0);
                agencyMapInfoList.get(x).put("nolinePumpNum",0);
            }
        }
        return R.ok().put("data",agencyMapInfoList);
    }

      /*
       * 水泵房设备组数据详情
       * @param
       * @return
       */
    @ApiOperation(value = "水泵房设备组数据详情")
    @RequestMapping(value = "/readPumpGroupInfoByHouse",method ={ RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name="houseId",value="id",required = true,dataType = "Long",paramType="form"),
    })
    public R readWaterPumpGroupInfoByHouse(Long houseId){
        Assert.parameterIsNull(houseId,"水泵房id不能为空");
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("houseId",houseId);
        List<Map<String,Object>> houseWaterPumpGroupList = waterPumpGroupService.readHousePumpGroupDetail(paramMap);
        return R.ok().put("data",houseWaterPumpGroupList);
    }

    @ApiOperation(value = "监控首页 设备在线离线个数")
    @RequestMapping(value = "/readWaterPumpStatusCount",method ={ RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name="isResultDesc",value="是/否返回结果字段描述(1/2)",required = false,dataType = "int",paramType="form"),
    })
    public R readWaterPumpStatusCount(Integer isResultDesc){
        Integer roleType =null;
        Long roleId =null;
        String companyCode =null;
        String agencyIdsStr = null;// 角色 权限内 水泵房id字符串
        List<Long> roleWaterPumpGroupIdList = null;// 角色 权限内 水泵组id集合
        Integer totalPumpNum = 0;
        Integer onLinePumpNum = 0;
        Map<String,Object> resultMap = new HashMap<String,Object>();
        R resultR = R.ok();
        if(isResultDesc!=null&&isResultDesc==1){
            resultR.put("desc",readWaterPumpStatus());
        }
        try {
            roleType = getCurrentRoleType();
            roleId = getCurrentRoleId();
            companyCode = getCurrentCompanyCode();
        }catch (NumberFormatException ex){
            return  R.error(400,"请重新登录");
        }
        if(roleId==null||roleType==null||companyCode==null){
            return  R.error(400,"请重新登录");
        }
        if(roleType!=1) {// 自定义角色
            agencyIdsStr = groupIotAgencyService.getAgencyIdsStrByGroupId( roleId+ "");
            Assert.parameterIsBlank(agencyIdsStr,"您暂无机构权限，请联系管理员");
            roleWaterPumpGroupIdList = waterPumpGroupService.getGroupIdListByHouseId(agencyIdsStr);
            if(roleWaterPumpGroupIdList==null||roleWaterPumpGroupIdList.isEmpty()){// 未查询到 水泵组 直接返回空数据
                resultMap.put("onLine",0);
                resultMap.put("offLine",0);
                resultMap.put("repairStatus",0);
                resultMap.put("alarmStatus",0);
                return resultR.put("data",resultMap);
            }
        }
        Wrapper<Map<String,Object>> wr = new EntityWrapper<Map<String,Object>>();
        wr.eq("wpGroup.company_code",companyCode);
        if(roleWaterPumpGroupIdList!=null && !roleWaterPumpGroupIdList.isEmpty() ){
            wr.in("wpGroup.group_id", roleWaterPumpGroupIdList);
        }
        totalPumpNum = waterPumpGroupService.selectWaterPumpStatusCount(wr);
        wr.eq("wpGroupData.deviceStatus",0);// 设备状态
        onLinePumpNum = waterPumpGroupService.selectWaterPumpStatusCount(wr);
        resultMap.put("onLine",onLinePumpNum);
        resultMap.put("offLine",totalPumpNum - onLinePumpNum);

        // 查询 角色 报修未读记录
        Wrapper<IotRepairDeclare> repairDeclareWp = new EntityWrapper<IotRepairDeclare>();
        repairDeclareWp.eq("company_code",companyCode);
        repairDeclareWp.eq("role_id",roleId);
        repairDeclareWp.eq("is_read",2);// 查询未读
        if(roleWaterPumpGroupIdList!=null && !roleWaterPumpGroupIdList.isEmpty() ){
            wr.in("group_id", roleWaterPumpGroupIdList);
        }
        Integer noReadRepairNum =iotRepairDeclareService.selectCount(repairDeclareWp);
        if(noReadRepairNum>0){
            resultMap.put("repairStatus",1);
        }else{
            resultMap.put("repairStatus",0);
        }
        resultMap.put("noReadRepairNum",noReadRepairNum);
        // 查询 角色 报警 未读记录
        EntityWrapper<Map<String, Object>> alarmRecordWp = new EntityWrapper<Map<String, Object>>();
        alarmRecordWp.eq("wpg.company_code",companyCode);
        if(roleWaterPumpGroupIdList!=null && !roleWaterPumpGroupIdList.isEmpty() ){
            wr.in("wpg.group_id", roleWaterPumpGroupIdList);
        }
        alarmRecordWp.eq("ar.is_reade",2);
        Integer noReadAlarmRecordNum =iotAlarmRecordService.selectNoReadAlarmRecordCount(alarmRecordWp);
        if(noReadAlarmRecordNum>0){
            resultMap.put("alarmStatus",1);
        }else{
            resultMap.put("alarmStatus",0);
        }
        resultMap.put("noReadAlarmRecordNum",noReadAlarmRecordNum);
        return resultR.put("data",resultMap);
    }

    /**
     * 监控首页 设备在线离线个数 结果描述
     * @return
     */
    public static String readWaterPumpStatus(){
        return "repairStatus-报修状态(0-无未读消息,1-有未读消息)，alarmStatus -报警状态(1/0-有/无未读消息),onLine-在线设备组数量，offLine-离线设备组数量"
                +"noReadAlarmRecordNum-未阅读的报警记录数量，noReadRepairNum-未阅读的报修记录数量";
    }
}
